from apps.users.models import User
from datetime import date
from rest_framework.response import Response
from rest_framework.views import APIView  # 基类
from rest_framework.generics import GenericAPIView  # 一般要设置序列化器和查询结果集 一般和mixin配合使用
from rest_framework.generics import ListAPIView  # get方法都不用写
from rest_framework.viewsets import ModelViewSet  # 增删改查


# 选哪个 都不是错误 就是合适与不合适
class DailyActiveCountAPIView(APIView):
    # class DailyActiveCountAPIView(GenericAPIView):
    def get(self, request):
        today = date.today()
        count = User.objects.filter(last_login__gte=today).count()

        return Response({'count': count})


class DailyOrderCountAPIView(GenericAPIView):
    """
    为什么 GenericAPIView 也是可以的.文档不是要求 GenericAPIView 必须设置 queryset和serialzier_class 吗???
    我们当前在get方法中,并没有用到 queryset 和 serializer_class 相关的属性和方法
    """

    def get(self, request):
        today = date.today()
        count = User.objects.filter(orderinfo__create_time__gte=today).count()

        return Response({'count': count})


"""
需求:     获取月增(每一天增加了多少用户)用户统计

前端:

后端:
   请求
                GET 
   业务逻辑
            1. 获取当天的日期
            2. 获取30天前的日期
            3. 遍历 每一天
                获取每一天的用户增量.增量查询的条件 应该是 日期是 2021-5-20 00:00:00  ~ 2021-5-21 00:00:00 范围内的
   响应 
        [
            {
                date:
                count:
            }
        ]
"""
from datetime import timedelta


class MonthAddCountAPIView(APIView):
    def get(self, request):
        # 1.获取当天的日期
        today = date.today()
        # 2. 获取30天前的日期
        start_date = today - timedelta(days=30)  # 2021-4-20

        date_list = []
        # 3. 遍历 每一天
        for i in range(30):
            # 获取每一天的用户增量
            # 增量查询的条件 应该是 日期是 2021-4-20 00:00:00  ~ 2021-4-21 00:00:00 范围内的
            begin_date = start_date + timedelta(days=i)
            end_date = start_date + timedelta(days=(i + 1))

            count = User.objects.filter(date_joined__gt=begin_date,
                                        date_joined__lt=end_date).count()

            date_list.append({
                'date': begin_date,
                'count': count
            })
        return Response(date_list)
